<?php

/**
 * 微信挖宝 Service
 * 
 * Apps/Common/Service/WxEventTreasureService.class.php
 * Zix @ 2015-08-26
 */

namespace Common\Service;

class WxEventTreasureService {

  private static $instance;
  var $name = '挖宝';
  var $type = 'Treasure';
  
  const POINT_THRESHOLD = 1200  ;

  
  public static function instance() {
    if (self::$instance == null) {
      $instance = new WxEventTreasureService();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'id' => '',
      'mer_id' => '',
      'name' => '',
      'icon' => '',
      'share_desc' => '',
      'rule' => '',
      'share_url' => '',
      'start_time' => '',
      'end_time' => '',
      'daily_times' => '0',
      'total_times' => '1',
      'award_times' => '1',
      'init_min_point' => 10,
      'init_max_point' => 50,
      'inc_point_rate' => 50,
      'inc_min_point' => 20,
      'inc_max_point' => 100,
      'dec_point_rate' => 50,
      'dec_min_point' => 20,
      'dec_max_point' => 100,
      'total_actvei_user' => 0,
      'threshold' => 1200 , 
    );
  }

  function get_by_id($id) {
    $WxEventTreasure = M('WxEventTreasure');
    $data = $WxEventTreasure->find($id);
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'mer_id' => '',
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
    );

    $config = extend($config, $default);

    $WxEventTreasure = M('WxEventTreasure');

    $where = array();

    if (!empty($config['status'])) {
      $where['status'] = $config['status'];
    }
    
    if (!empty($config['mer_id'])) {
      $where['mer_id'] = $config['mer_id'];
    }
    
    if ($config['count']) {
      return $WxEventTreasure->where($where)->count();
    } else {
      $order = $config['sort'] . ' ' . $config['order'];
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ' , ' . $config['page_size'];
      $data = $WxEventTreasure
          ->where($where)
          ->limit($limit)->order($order)->select();
      //echo $WxEventTreasure->_sql();
      return $data ? $data : array();
    }
  }

  function create($data, $is_ajax = true) {
    $WxEventTreasure = M('WxEventTreasure');
    $ret = $WxEventTreasure->add($data);
    if ($is_ajax) {
      if ($ret) {
        return ajax_arr('添加成功', TRUE, array(
          'id' => $ret
        ));
      } else {
        return ajax_arr('添加失败', FALSE);
      }
    } else {
      if ($ret) {
        return $ret;
      } else {
        return 0;
      }
    }
  }

  function update($id, $data) {
    $WxEventTreasure = M('WxEventTreasure');

    $ret = $WxEventTreasure->where("id = %d", $id)->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    $WxEventTreasure = M('WxEventTreasure');
    $ret = $WxEventTreasure->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }

  /**
   * 开始助力
   * @param type $event_id
   * @param type $user_id
   * @param type $assist_user_id
   * @return type
   */
  function do_assist( $event_id , $user_id , $assist_user_id  ) {
    //检查是否已经助力过了
    $WxEventTreasureUserAssist = M('WxEventTreasureUserAssist');
    $has_assist = $WxEventTreasureUserAssist->where(array(
      'user_id' => $user_id ,
      'assist_user_id' => $assist_user_id ,
      'event_id' => $event_id ,
    ))->find();
    
    //echo $WxEventTreasureUserAssist->_sql() ;
    
    if ( !empty($has_assist ) ) {
      return ajax_arr('已经帮TA挖过了');
    }
    
    //取用户信息
    $MerUser = M('MerUser');
    $user_data = $MerUser->where('id = %d' , $user_id )->find();
    
    //取活动
    $event_data = $this->get_by_id($event_id);
    
    //取个人数据
    $WxEventTreasureUser = M('WxEventTreasureUser');
    $assist_user_data = $WxEventTreasureUser->where(array(
      'user_id' => $assist_user_id ,
      'event_id' => $event_id ,
    ))->find();
    
    $my_point = $assist_user_data['point'];
    $inc_point_rate = $event_data['inc_point_rate'];
    $dec_point_rate = $event_data['dec_point_rate'];
    $is_good_card = FALSE ;
    $rate_rand = mt_rand(1, 100);
    $good_point = mt_rand($event_data['inc_min_point'], $event_data['inc_max_point']);
    $bad_point = mt_rand($event_data['dec_min_point'], $event_data['dec_max_point']) ;
    
    $threshold = $event_data['threshold'];
    
    if ( $my_point >= $threshold ) {
      //特殊处理
      if( $rate_rand >= $dec_point_rate ) {
        //好人卡
        $is_good_card = TRUE  ;
      }
    } else {
      if ( $rate_rand <= $inc_point_rate ) {
        //好人卡
        $is_good_card = TRUE ;
      }
    }    
    
    //处理结果
    if ( $is_good_card ) {
      $sql = "update wx_event_treasure_user set point = point + $good_point , assist_num = assist_num + 1 where user_id = $assist_user_id and event_id = $event_id " ;
      $point = $good_point ;
    } else {
      $sql = "update wx_event_treasure_user set point = point - $bad_point , assist_num = assist_num + 1 where user_id = $assist_user_id and event_id = $event_id " ;
      $point = $bad_point * -1 ;
    }
    
    $data = array(
      'event_id' => $event_id ,
      'assist_user_id' => $assist_user_id ,
      'user_id' => $user_id ,
      'nickname' => $user_data['nickname'] ,
      'icon' => $user_data['icon'] ,
      'point' => $point
    );
    
    $WxEventTreasureUserAssist->startTrans();
    $ret1 = $WxEventTreasureUserAssist->add($data);
    $ret2 = $WxEventTreasureUserAssist->execute($sql);
    
    if ( $ret1 && $ret2 ) {
      $WxEventTreasureUserAssist->commit();
      return ajax_arr('OK' , TRUE , array(
        'point' => $point ,
        'is_good_card' => $is_good_card ,
      ));
    } else {
      $WxEventTreasureUserAssist->rollback();
      return ajax_arr('发生错误，请稍后再试');
    }
  }
  
  function take_award($event_id  , $user_id , $award_id ) {
    $event_data = $this->get_by_id($event_id);
    
    if( strtotime($event_data['end_time']) < time() ) {
      return ajax_arr('活动已经结束了');
    }
    
    $WxEventTreasureUser = WxEventTreasureUserService::instance();
    $user_data = $WxEventTreasureUser->get_by_uid($user_id, $event_id);
    if ( !empty( $user_data['award_id'] ) ) {
      return ajax_arr('你已经兑换过奖品了');
    }
    
    //取礼品
    $WxEventTreasureAward = WxEventTreasureAwardService::instance();
    $award_data = $WxEventTreasureAward->get_by_id($award_id);
    if( $award_data['remain_qty'] <= 0 ) {
      return ajax_arr('奖品已经发光了');
    }
    
    $data = array(
      'award_id'   => $award_id ,
      'award_name' => $award_data['name'] ,
      'award_time' => date('Y-m-d H:i:s'),
    );
    $TreasureUser    = M('WxEventTreasureUser');
    $TreasureAward   = M('WxEventTreasureAward');
    $TreasureAwardSn = M('WxEventTreasureAwardSn');
    
    $TreasureUser->startTrans();
    $ret1 = TRUE ;

    if (  $award_data['valid_type'] == 1 ) {
      //取兑换码
      $sn_data = $TreasureAwardSn->where('award_id = %d and status = 0' , $award_id )->find();
      
      if ( empty( $sn_data ) ) {
        $TreasureUser->rollback();
        return ajax_arr('兑换码未找到');
      }
      $ret1 = $TreasureAwardSn->where('id = %d' , $sn_data['id'])->save(array(
        'status' => 1 ,
        'take_time' => date('Y-m-d H:i:s'),
      ));
      $data['award_sn_id'] = $sn_data['id'];
      $data['award_sn'] = $sn_data['sn'];
    }
    
    $data['point'] = array('exp' , 'point - ' . $award_data['point'] );
    
    $ret2 = $TreasureUser->where('user_id = %d and event_id = %d' , $user_id , $event_id )->save($data );
    $ret3 = $TreasureAward->where('id = %d' , $award_id )->save(array(
      'taken_qty' => array('exp' , 'taken_qty + 1'),
      'remain_qty' => array('exp' , 'remain_qty - 1'),
    ));
    
    
    if( $ret1 && $ret2 && $ret3 ) {
      $TreasureUser->commit();
      return ajax_arr('成功' , TRUE , array(
        'award_name' => $award_data['name']
      ));
    } else {
      $TreasureUser->rollback();
      return ajax_arr('兑换失败，请稍后再试');
    }
    
  }
}
